using System;
using System.Linq;
using PicoContainer.Defaults;
using XEvolve.Core.Runtime;
using XEvolve.Core.SPI;

namespace XEvolve.Core.Pico
{
    internal class PicoBasedServiceRegistry : IServiceRegistry, IServiceLocator
    {
        private readonly DefaultPicoContainer context;

        public PicoBasedServiceRegistry(DefaultPicoContainer context)
        {
            this.context = context;
        }

        public void RegisterService(Type api, Type implementation)
        {
            context.RegisterComponentImplementation(api, implementation);
        }

        public void RegisterService(Type api, object instance)
        {
            context.RegisterComponentInstance(api, instance);
        }

        public void Start()
        {
            foreach (var service in GetServices<IStartable>())
            {
                service.Start();
            }
        }

        public void Stop()
        {
            foreach (var service in GetServices<IStartable>())
            {
                try
                {
                    service.Stop();
                }catch (Exception)
                {
                }
            }
        }

        public Api GetService<Api>()
        {
            return (Api) context.GetComponentInstance(typeof (Api));
        }

        public Api[] GetServices<Api>()
        {
            return context.GetComponentInstancesOfType(typeof (Api)).Cast<Api>().ToArray();
        }
    }
}